////////////////////////////////////////////////////////////////////////
//
// BEGIN_COPYRIGHT
// Confidential property of Faxsun.
//
// Copyright 2014-
//
// Faxsun. All rights reserved.
//
// Unpublished rights reserved under Chinese copyright laws.
// END_COPYRIGHT
//
// BEGIN_DISCLAIMER
// This software contains confidential and trade secret information of 
// Faxsun. Use, duplication or disclosure of the software and 
// documentation by any individual, organization or government must be 
// granted written agreement from Faxsun.
//
// Faxsun. Shanghai China
// END_DISCLAIMER
//
////////////////////////////////////////////////////////////////////////

package com.faxsun.web.utils;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.faxsun.http.HttpInvoker;
import com.faxsun.web.pojos.WechatUserInfo;

/**
 * 微信公众号接口调用辅助类
 * 
 * @author bowen.sun
 *
 */
@Component
public class WechatApiUtils {

	private static final Logger log = LoggerFactory
			.getLogger(WechatApiUtils.class);

	@Value("${account.wechat.info.url}")
	private String WechatUserInfoUrl;

	@Value("${account.wechat.jsapi.sign.url}")
	private String WechatJsapiSignUrl;

	@Value("${image.wechat.download.url}")
	private String wechatImageApi;

	/**
	 * 获取用户信息
	 * 
	 * @param openId
	 * @return
	 */
	public WechatUserInfo getUserInfo(String openId) {
		String resultStr = HttpInvoker.get(WechatUserInfoUrl + "?openId="
				+ openId);
		return JSON.parseObject(resultStr, WechatUserInfo.class);
	}

	/**
	 * 获取jsapi签名
	 * <p>
	 * 返回json串，eg:{"signature":"bbb7bc06b0066a6980105b282f9b64d67ad97851",
	 * "appId":"wx469c080c43317288"}
	 * 
	 * @param nonceStr
	 * @param timestamp
	 * @param url
	 * @return
	 */
	public String getJsapiSign(String nonceStr, String timestamp, String url) {
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("url", url);
		paramMap.put("timestamp", timestamp);
		paramMap.put("nonceStr", nonceStr);

		return HttpInvoker.get(WechatJsapiSignUrl, paramMap);
	}

	/**
	 * 获取指定临时素材的url
	 * 
	 * @param mediaId
	 * @return
	 */
	public String getMediaUrl(String mediaId) {
		String upUrl = MessageFormat.format(this.wechatImageApi, mediaId);
		String url = HttpInvoker.get(upUrl);
		if (StringUtils.isEmpty(url)) {
			log.error("Get wechat image fail: wechat api url="+upUrl);
			return "";
		} else {
			return url;
		}
	}
}
